home *** CD-ROM | disk | FTP | other *** search
- // ArrayHeap.cp
- #define ArrayHeap_cp
-
- #ifndef ArrayHeap_h
- #include "ArrayHeap.h"
- #endif
-
- template < class Element >
- ArrayHeap<Element>::ArrayHeap( ArrayOf<Element> array,
- Comparison theComparison )
- : heap( array.Start() - 1 ),
- lastElement( array.Length() ),
- compare( theComparison )
- {
- this->MakeHeap();
- }
-
- template < class Element >
- void ArrayHeap<Element>::Sink( uint32 sinking )
- {
- Assert( sinking > 0 );
- Assert( sinking <= this->lastElement );
-
- Element sinkingElement = this->heap[ sinking ];
-
- while ( 2 * sinking <= this->lastElement )
- {
- uint32 rising = 2 * sinking;
-
- if ( rising < this->lastElement
- && this->compare( this->heap[ rising ], this->heap[ rising+1 ] ) < 0 )
- rising++;
-
- if ( this->compare( sinkingElement, this->heap[ rising ] ) >= 0 )
- break;
-
- this->heap[ sinking ] = this->heap[ rising ];
- sinking = rising;
- }
-
- this->heap[ sinking ] = sinkingElement;
- }
-
- template < class Element >
- void ArrayHeap<Element>::MakeHeap()
- {
- for ( uint32 i = this->lastElement / 2; i > 0; i-- )
- this->Sink( i );
- }
-
- template < class Element >
- void ArrayHeap<Element>::Pop()
- {
- Assert( this->lastElement > 0 );
- heap[ 1 ] = this->heap[ this->lastElement-- ];
- if ( this->lastElement > 1 )
- this->Sink( 1 );
- }
-
- template < class Element >
- void ArrayHeap<Element>::Sort()
- {
- while ( this->lastElement > 1 )
- {
- Element largest = this->Top();
- this->Pop();
- this->heap[ this->lastElement + 1 ] = largest;
- }
- this->lastElement = 0;
- }
-